package terra.model;

import java.io.Serializable;

import terra.definitions.NpcDef;
import terra.managers.DefManager;
import terra.managers.ThreadPoolManager;
import terra.model.object.GameObject;
import terra.model.object.NpcObject;
import terra.model.object.ai.AbstractAI;

public class SpawnPoint implements Runnable, Serializable {

	private static final long serialVersionUID = 1L;

	private int def;
	private int mapIndex;
	private float x, y;
	public int spawnTime = 60000;
	private GameObject spawned = null;

	@Override
	public void run() {
		NpcDef d = DefManager.npcDefs.get(def);
		NpcObject obj = null;
		AbstractAI ai = null;
		try {
			obj = (NpcObject) Class.forName(
					"terra.model.object." + d.getStringProperty("instance"))
					.newInstance();
			ai = (AbstractAI) Class.forName(
					"terra.model.object.ai." + d.getStringProperty("ai"))
					.newInstance();

		} catch (Exception e) {
			e.printStackTrace();
		}
		ai.setOwner(obj);
		obj.setSpawn(this);
		obj.setAi(ai);
		obj.setDef(d);
		obj.applyDef();
		obj.setX(getX());
		obj.setY(getY());
		obj.checkLocation();
		World.getInstance().addObject(obj.getObjectId(), obj);
		setSpawned(obj);
	}

	public float getX() {
		return x;
	}

	public void setX(float x) {
		this.x = x;
	}

	public float getY() {
		return y;
	}

	public void setY(float y) {
		this.y = y;
	}

	public void objectDied() {
		if (getSpawned() != null)
			ThreadPoolManager.getInstance().scheduleGeneral(this, spawnTime);
		setSpawned(null);
	}

	public int getDef() {
		return def;
	}

	public void setDef(int def) {
		this.def = def;
	}

	public int getMapIndex() {
		return mapIndex;
	}

	public void setMapIndex(int mapIndex) {
		this.mapIndex = mapIndex;
	}

	public GameObject getSpawned() {
		return spawned;
	}

	public void setSpawned(GameObject spawned) {
		this.spawned = spawned;
	}
}
